package 栈;

import java.util.Scanner;

public class 数组模拟栈 {
	public static void main(String[] args) {
		
		//创建栈
		ArrayStack stack = new ArrayStack(5);
		String key = "";
		boolean loop = true;
		Scanner  scanner = new Scanner(System.in);
		while(loop) {
			System.out.println("s 查看栈");
			System.out.println("push 入栈");
			System.out.println("pop 出栈");
			System.out.println("e 退出");
			key = scanner.next();
			switch (key) {
			case "s":
				stack.showStack();
				break;
			case "push":
				System.out.println("入栈数据:");
				int data = scanner.nextInt();
				stack.push(data);
				break;
			case "pop":
				try {
					int d = stack.pop();
					System.out.println(d);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case "e":
				loop = false;
				break;
			default:
				break;
			}
		}
	}
}

class ArrayStack{
	private int maxSize;
	private int[] stack;
	private int top;
	
	public ArrayStack() {
		super();
	}

	public ArrayStack(int maxSize) {
		this.maxSize = maxSize;
		stack = new int[maxSize];
		top = -1;
	}
	
	//栈空
	public boolean isEmpty() {
		return top == -1;
	}
	//栈满
	public boolean isFull() {
		return top == maxSize - 1;
	}
	
	//入栈
	public void push(int data) {
		if(isFull()) {
			System.out.println("栈满！");
			return;
		}
		
		top++;
		stack[top] = data;
	}
	
	//出栈
	public int pop() {
		if(isEmpty()) {
			throw new RuntimeException("栈空！");
		}
		
		int data = stack[top];
		top--;
		return data; 
	}
	
	//显示栈，从栈顶开始，就是数组尾部
	public void showStack() {
		if(isEmpty()) {
			System.out.println("栈空！");
			return ;
		}
		
		for(int i = top; i >= 0;i--) {
			System.out.println("stack["+ stack[i] +"]");
		}
	}
}